package com.eleven.trades.utils;

import com.eleven.trades.error.BusinessException;
import com.eleven.trades.result.ResultCode;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class CommonUtils {
    /**
     * 对明文字符串进行加密
     * @param source
     * @return
     */
    public static String md5(String source) throws BusinessException {
        if(source==null || source.length()==0)
        {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK);

        }
        //2 获取messageDigest对象
        String algorithm ="md5";
        try{
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            //3 获取明文字符串对应的字节数组
            byte[]  input = source.getBytes();
            //4加密
            byte[]  output= messageDigest.digest(input);
            // 5 创建BigInteger对象存放加密后的字节数组
            int signum=1;
            BigInteger bigInteger= new BigInteger(signum,output);
            //6  按照16禁止 将bigInteger转化为字符串
            int radix =16;
            String encoded = bigInteger.toString(radix).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
